/* eslint-disable max-len */
/* eslint-disable import/order */
import React, { useEffect, useCallback } from 'react';
import { observer } from 'mobx-react-lite';
import { Action } from '@choerodon/master';
import { useDetailStore } from '../../stores/index';
import { get } from '@choerodon/inject';
import { Loading } from '@choerodon/components';
import { Tooltip } from 'choerodon-ui/pro/lib';
import StatusDot from './statusDot';
import { Modal } from 'choerodon-ui/pro';
import moment from 'moment';
import { timeConverts } from '@/utils/index';
import CodeLog from './codeLog';
import AduitModal from '../audit-modal';
import StatusTag from '../../../deployment-list/components/StatusTag';
import { checkLog, checkStaus, persionCheck } from './service';

import './index.less';

interface Iprops{

}
const Index:React.FC<Iprops> = (props:Iprops) => {
  const {
    recordDetailDs,
    projectId,
    realName,
    siderDs,
    pipDetailDs,
  } = useDetailStore();
  const rdDs:any = recordDetailDs && recordDetailDs.toData()[0];
  const {
    stageRecordList,
    triggerType,
    trigger,
    startedDate,
    finishedDate,
    id: recordId,
    status: statuss,
    name: pipName,
  } = rdDs || {};
  const maps:any = new Map([
    ['manual', '手动触发'],
    ['schedule', '定时触发'],
    ['app_version', '应用服务版本触发'],
    ['api', 'api触发'],
  ]);
  useEffect(() => {

  });
  // 渲染三点操作----对应的操作
  const renderFooterBtns = useCallback((type:String, status:String, id:string, name?:any, audit?:any) => {
    let actionData:object[] = [];
    switch (status) {
      case 'created':
        break;
      case 'pending':
        break;
      case 'running':
        break;
      case 'skipped':
      case 'success':
      case 'failed':
        actionData = [
          {
            service: ['choerodon.code.project.deploy.continuous-deployment.ps.queryLog'],
            text: '查看日志',
            action: () => openLogModel(id, name),
          },
        ];
        break;
      case 'stop':
        break;
      case 'canceled':
        break;
      case 'not_audit':
        if (type === 'cd_audit') {
          audit?.canAuditFlag ? actionData = [
            {
              service: [
                'choerodon.code.project.deploy.continuous-deployment.ps.audit',
              ],
              text: '人工审核',
              action: () => handlePersonCheck(id, name),
            },
          ] : actionData = [];
        }
        break;
    }
    return <Action data={actionData} />;
  }, []);
  // 刷新
  const refresh = () => {
    siderDs.query();
    recordDetailDs.setQueryParameter('id', recordId);
    recordDetailDs.query();
    pipDetailDs.query();
  };
    // 查看日志
  const openLogModel = (id:string, name:string) => {
    Modal.open({
      key: Modal.key(),
      title: '查看日志',
      // @ts-ignore
      children: <CodeLog ids={id} jobName={name} projectId={projectId} />,
      style: {
        width: 'calc(100vw - 3.52rem)',
      },
      drawer: true,
      okText: '下载日志',
      cancelText: '关闭',
    });
  };

  // 人工审核
  const handlePersonCheck = (id:string, jobName:string) => {
    const name = recordDetailDs?.current?.get('name');
    Modal.open({
      key: Modal.key(),
      title: '人工审核',
      children: <AduitModal
        name={name}
        taskRecordId={id}
        onClose={refresh}
        jobName={jobName}
        checkStatus={checkStaus}
        persionCheck={persionCheck}
      />,
      movable: false,
    });
  };
  // 渲染job名称
  const getJobName = (type:string, name:string) => {
    const Type:any = {
      cd_chart_deploy: 'chart包',
      cd_audit: '人工卡点',
    };
    if (type) {
      return (
        <span>
          【
          {Type[type]}
          】
          {name}
        </span>
      );
    }
    return (
      <span>{name}</span>
    );
  };
  // 渲染每一个模块的内容
  const renderContent = (type:string, auditConfig?:any, chartDeployCfg?:any) => {
    if (type === 'cd_chart_deploy') {
      if (chartDeployCfg) {
        return (
          <div className="c7n-piplineManages-detail-column-lists-item-details">
            <div>
              <span className="span-details"> 应用服务：</span>
              {chartDeployCfg.appServiceName ? (
                <Tooltip title={chartDeployCfg.appServiceName} placement="topLeft">
                  {chartDeployCfg.appServiceName}
                </Tooltip>
              ) : '-'}
            </div>
            <div>
              <span className="span-details"> 服务版本：</span>
              {chartDeployCfg.appServiceVersion ? <Tooltip title={chartDeployCfg.appServiceVersion} placement="topLeft">{chartDeployCfg.appServiceVersion}</Tooltip> : '-'}
            </div>
            <div>
              <span className="span-details"> 部署环境：</span>
              {chartDeployCfg.envName ? <Tooltip title={chartDeployCfg.envName} placement="topLeft">{chartDeployCfg.envName}</Tooltip> : '-'}
            </div>
          </div>
        );
      }
      return '';
    } if (type === 'cd_audit') {
      if (auditConfig) {
        return (
          <div className="c7n-piplineManages-detail-column-lists-item-detail">
            <div>
              <span className="span-details"> 指定审核人员：</span>
              {auditConfig.appointUsers && auditConfig.appointUsers !== 0 ? auditConfig.appointUsers
                .map((item:any, index:number) => (
                  <span style={{
                    background: 'rgba(15,19,88,0.06)', display: 'inline-block', marginRight: '3px', padding: '0 4px', marginTop: '3px',
                  }}
                  >
                    { item.realName }
                  </span>
                )) : '-'}
            </div>
            <div>
              <span className="span-details"> 已审核人员：</span>
              {auditConfig.reviewedUsers && auditConfig.reviewedUsers.length !== 0
                ? auditConfig.reviewedUsers
                  .map((item:any, index:number) => (
                    <span style={{
                      background: 'rgba(15,19,88,0.06)', display: 'inline-block', marginRight: '3px', padding: '0 4px',
                    }}
                    >
                      { item.realName }
                    </span>
                  )) : '-'}
            </div>
            <div>
              <span className="span-details"> 审核模式：</span>
              {auditConfig.countersigned ? '会签' : '或签'}
            </div>
          </div>
        );
      }
      return '';
    }
    return '';
  };
  // 获取持续时间
  const getDurationTime = (finish:any, start:string) => {
    if (!finish || !start) {
      return '-';
    }
    return timeConverts(moment(finish).diff(moment(start), 'seconds'));
  };
  // 获取api触发信息
  const getInfo = (info:any, type:string) => {
    if (type === 'api') {
      return (
        <span>
          {info.realName}
        &nbsp;.&nbsp;
        </span>
      );
    }
    return '';
  };
  return (
    <div className="c7n-piplineManages">
      {(!recordDetailDs || recordDetailDs.status !== 'ready')
        ? <Loading display type={get('configuration.master-global:loadingType') || 'c7n'} />
        : (
          <>
            <div className="c7n-piplineManages-header-title">
              <div className="c7n-piplineManages-header-title-info">
                基本信息
              </div>
              <div className="c7n-piplineManages-header-title-stage">
                阶段
              </div>
            </div>
            <div className="c7n-piplineManages-content">
              <div className="c7ncd-piplineManages-detail-info">
                <div className={`c7ncd-piplineManages-detail-info-detail c7ncd-piplineManages-detail-info-detail-${statuss}`}>
                  <div className="c7ncd-piplineManages-detail-info-detail-line" />
                  <div className="c7ncd-piplineManages-detail-info-detail-title">
                    <div>
                      <Tooltip title={pipName} placement="top">
                        {pipName}
                      </Tooltip>
                    </div>
                    <div>
                      <StatusTag status={statuss} />
                    </div>
                  </div>
                  <div className="c7ncd-piplineManages-detail-info-detail-content">
                    <div>
                      <span className="span-label"> 触发规则：</span>
                      {getInfo(trigger, triggerType)}
                      <Tooltip title={maps.get(triggerType)} placement="top">
                        {maps.get(triggerType)}
                      </Tooltip>
                    </div>
                    <div>
                      <span className="span-label"> 开始时间：</span>
                      {startedDate || '-'}
                    </div>
                    <div>
                      <span className="span-label"> 结束时间：</span>
                      {finishedDate || '-'}
                    </div>
                  </div>
                </div>
              </div>
              <div className="c7n-piplineManages-detail">
                {stageRecordList && stageRecordList.map((
                  {
                    name,
                    status,
                    jobRecordList,
                  }:any, index:number,
                ) => (
                  <div
                    className={`c7n-piplineManages-detail-column c7n-piplineManages-detail-column-${status}`}
                  >
                    <div className="c7n-piplineManages-detail-column-header">
                      <Tooltip title={name}>
                        <span>{name}</span>
                      </Tooltip>
                    </div>
                    <div className="c7n-piplineManages-detail-column-lists">
                      <h6>
                        任务列表
                      </h6>
                      {jobRecordList && jobRecordList.map(({
                        name: jobName,
                        status: statusJob,
                        audit,
                        id,
                        type: jobType,
                        startedDate: start,
                        finishedDate: finish,
                        deployInfo,
                      }:any, jobIndex:number) => (
                        <div className="c7n-piplineManages-detail-column-lists-item">
                          <div className="c7n-piplineManages-detail-column-lists-item-sub">
                            <StatusDot
                              size={13}
                              status={statusJob}
                              style={{ lineHeight: '22px', marginRight: '4px' }}
                            />
                            <Tooltip title={jobName}>
                              {getJobName(jobType, jobName)}
                            </Tooltip>
                          </div>
                          {startedDate && (
                          <Tooltip title={start}>
                            <div className="c7n-piplineManages-detail-column-lists-item-date">
                              {start}
                            </div>
                          </Tooltip>
                          )}
                          {renderContent(jobType, audit, deployInfo)}
                          <footer>
                            <span className="c7n-piplineManages-detail-column-lists-item-time">
                              {renderFooterBtns(jobType, statusJob, id, jobName, audit)}
                              <span className="c7n-piplineManages-detail-column-lists-item-time-name">任务耗时：</span>
                              <span className="c7n-piplineManages-detail-column-lists-item-time-duration">
                                <Tooltip title={getDurationTime(finish, start)} placement="topLeft">
                                  {getDurationTime(finish, start)}
                                </Tooltip>
                              </span>
                            </span>
                          </footer>
                        </div>
                      ))}
                    </div>
                    <div className="c7n-piplineManages-detail-column-type">
                      <svg xmlns="http://www.w3.org/2000/svg" width="28" height="9" viewBox="0 0 28 9">
                        <path fill="#6887E8" d="M511.5,131 L520.5,135.5 L511.5,140 L511.5,136 L493,136 L493,135 L511.5,135 L511.5,131 Z" transform="translate(-493 -131)" />
                      </svg>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </>
        )}
    </div>
  );
};
export default observer(Index);
